package com.chuantou.yuba.ui;

import java.util.HashMap;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.NewsTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.fragment.NewsDetailFragment;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.UiUtil;

public class NewsDetailActivity extends BaseActionBarActivity implements OnClickListener {
	private TextView mSendView;
	private EditText mCommentView;
	private NewsTO mNews;
	private NewsDetailFragment mDetailFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_detail);
		setupViews();
		setTitle("");
	}

	private void setupViews() {
		mSendView = (TextView) findViewById(R.id.send);
		mSendView.setOnClickListener(this);
		mSendView.requestFocus();
		mCommentView = (EditText) findViewById(R.id.comment);
		mNews = getIntent().getParcelableExtra(Constants.EXTRA_DATA);
		ViewGroup contentLayout = (ViewGroup) findViewById(R.id.content);
		contentLayout.removeAllViews();
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		mDetailFragment = new NewsDetailFragment();
		mDetailFragment.setArguments(getIntent().getExtras());
		transaction.add(R.id.content, mDetailFragment, NewsDetailFragment.class.getName());
		transaction.commitAllowingStateLoss();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send:
			String content = mCommentView.getText().toString().trim();
			sendComment(content);
			break;

		default:
			break;
		}
	}

	private void sendComment(final String content) {
		if (UiUtil.isFastDoubleClick())
			return;
		if (TextUtils.isEmpty(content)) {
			Toast.makeText(this, R.string.comment_input_length_error, Toast.LENGTH_SHORT).show();
			return;
		}
		// 先判断是否已经登录
		AccountManager manager = AccountManager.getInstance(getApplicationContext());
		if (manager.isLogined()) {
			UserTO user = manager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(this, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			} else {
				String requestUrl = UriHelper.getSendNewsCommentUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_CONTENT, content);
				params.put(UriHelper.PARAMS_TOKEN, user.getToken());
				params.put(UriHelper.PARAMS_ID, String.valueOf(mNews.getId()));
				params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, requestUrl, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (!hasDestroyed()) {
							if (response != null) {
								if (response.isSuccess()) {
									mCommentView.setText("");
									UiUtil.hideInputKeyboard(getApplicationContext(), mCommentView);
									Toast.makeText(NewsDetailActivity.this, R.string.comment_send_success, Toast.LENGTH_SHORT).show();
									mDetailFragment.reload();
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(NewsDetailActivity.this, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(NewsDetailActivity.this, -1, LoginActivity.ACTION_RETURN);
									} else {
										String msg = response.getMsg();
										msg = TextUtils.isEmpty(msg) ? getString(R.string.comment_send_failed) : msg;
										Toast.makeText(NewsDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								Toast.makeText(NewsDetailActivity.this, R.string.comment_send_failed, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (!hasDestroyed()) {
							Toast.makeText(NewsDetailActivity.this, R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(getApplicationContext(), request);
				Toast.makeText(this, R.string.comment_sending, Toast.LENGTH_SHORT).show();
			}
		} else {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
		}
	}
}
